package com.hsxc.cdz.monitor;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.impl.Log4JLogger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.hsxc.cdz.mgmt.GlobalManager;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @author 刘力文
 *         netty 服务器实体类
 */
@Component
public class Server {

    /********************************************************************/
    //私有属性
    private Logger logger = LoggerFactory.getLogger(Server.class);
    private static final int port = 5000;
    private static final int port2 = 2816;
    private EventLoopGroup boss = new NioEventLoopGroup();
    private EventLoopGroup work = new NioEventLoopGroup();

    /********************************************************************/
    //自动注入属性
    @Autowired
    MyChannelInitializer myChannelInitializer;

    /********************************************************************/
    //类加载初始化方法
    @PostConstruct
    public void start() {
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.option(ChannelOption.SO_BACKLOG, 128);
            bootstrap.option(ChannelOption.TCP_NODELAY, true);
            bootstrap.group(boss, work);
            bootstrap.channel(NioServerSocketChannel.class);
            bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
            bootstrap.childHandler(myChannelInitializer);
            ChannelFuture future = bootstrap.bind(port).sync();
            //ChannelFuture future2 = bootstrap.bind(port2).sync();
            if (future.isSuccess()) {
               logger.info("netty服务器启动成功");
            }
            /*if(future2.isSuccess()){
				System.out.println("netty服务器第二个端口已启动");
			}*/
        } catch (InterruptedException e) {
            logger.error("服务器启动失败");
            work.shutdownGracefully();
            boss.shutdownGracefully();
        }
    }

    @PreDestroy
    public void destroy() {
        GlobalManager.pileManager.logoutAll();
        work.shutdownGracefully();
        boss.shutdownGracefully();
    }
}
